// HMI系统状态管理Hook

import { useState, useEffect, useCallback } from 'react';

// 内联类型定义，避免导入问题
interface VehicleStatus {
  speed: number;
  speedLimit: number;
  gear: 'P' | 'R' | 'N' | 'D';
  battery: number;
  temperature: number;
  autonomousMode: boolean;
  emergencyStop: boolean;
  cruiseSpeed?: number;
}

interface NavigationInfo {
  destination: string;
  distance: number;
  eta: number;
  currentStreet: string;
  nextTurn: string;
  turnDistance: number;
}

interface ModuleStatus {
  camera: 'online' | 'offline' | 'warning';
  lidar: 'online' | 'offline' | 'warning';
  radar: 'online' | 'offline' | 'warning';
  gps: 'online' | 'offline' | 'warning';
  imu: 'online' | 'offline' | 'warning';
  can: 'online' | 'offline' | 'warning';
  perception: 'online' | 'offline' | 'warning';
  planning: 'online' | 'offline' | 'warning';
  control: 'online' | 'offline' | 'warning';
}

interface SystemMessage {
  id: string;
  type: 'info' | 'warning' | 'error' | 'success';
  title: string;
  message: string;
  timestamp: Date;
  acknowledged: boolean;
}

interface UserRole {
  type: 'passenger' | 'safety_officer';
  name: string;
  permissions: string[];
}

interface DetectedObject {
  id: string;
  type: 'pedestrian' | 'vehicle' | 'bicycle' | 'animal' | 'unknown';
  position: { x: number; y: number; z: number };
  confidence: number;
  distance: number;
  velocity: number;
}

interface ControlSettings {
  volume: number;
  brightness: number;
  language: 'zh' | 'en';
  theme: 'light' | 'dark' | 'auto';
  fontSize?: 'small' | 'medium' | 'large' | 'xlarge';
}

// 内联模拟数据生成函数
const generateMockVehicleStatus = (): VehicleStatus => ({
  speed: Math.floor(Math.random() * 60) + 20,
  speedLimit: 50,
  gear: 'D',
  battery: Math.floor(Math.random() * 30) + 70,
  temperature: Math.floor(Math.random() * 10) + 20,
  autonomousMode: true,
  emergencyStop: false,
  cruiseSpeed: 45,
});

const generateMockNavigationInfo = (): NavigationInfo => ({
  destination: '软通动力大厦',
  distance: 2.5,
  eta: 8,
  currentStreet: '滨海大道',
  nextTurn: '右转进入科技园',
  turnDistance: 300,
});

const generateMockModuleStatus = (): ModuleStatus => ({
  camera: Math.random() > 0.9 ? 'warning' : 'online',
  lidar: Math.random() > 0.95 ? 'offline' : 'online',
  radar: Math.random() > 0.9 ? 'warning' : 'online',
  gps: 'online',
  imu: 'online',
  can: Math.random() > 0.95 ? 'warning' : 'online',
  perception: 'online',
  planning: 'online',
  control: 'online',
});

const generateMockSystemMessages = (): SystemMessage[] => [
  {
    id: '1',
    type: 'info',
    title: '自动驾驶模式激活',
    message: '车辆已进入自动驾驶模式，请系好安全带',
    timestamp: new Date(Date.now() - 1000 * 60 * 5),
    acknowledged: false,
  },
  {
    id: '2',
    type: 'success',
    title: '系统自检完成',
    message: '所有系统模块运行正常',
    timestamp: new Date(Date.now() - 1000 * 60 * 3),
    acknowledged: true,
  },
];

const generateMockUserRole = (): UserRole => ({
  type: 'safety_officer',
  name: '安全员',
  permissions: ['view_all', 'control_vehicle', 'emergency_stop'],
});

const generateMockDetectedObjects = (): DetectedObject[] => [
  {
    id: '1',
    type: 'vehicle',
    position: { x: 10, y: 5, z: 0 },
    confidence: 0.95,
    distance: 15,
    velocity: 30,
  },
  {
    id: '2',
    type: 'pedestrian',
    position: { x: -5, y: 8, z: 0 },
    confidence: 0.88,
    distance: 12,
    velocity: 5,
  },
];

const generateMockControlSettings = (): ControlSettings => ({
  volume: 70,
  brightness: 80,
  language: 'zh',
  theme: 'dark',
  fontSize: 'medium',
});

export const useHmiState = () => {
  const [vehicleStatus, setVehicleStatus] = useState<VehicleStatus>(generateMockVehicleStatus());
  const [navigationInfo, setNavigationInfo] = useState<NavigationInfo>(generateMockNavigationInfo());
  const [moduleStatus, setModuleStatus] = useState<ModuleStatus>(generateMockModuleStatus());
  const [systemMessages, setSystemMessages] = useState<SystemMessage[]>(generateMockSystemMessages());
  const [userRole, setUserRole] = useState<UserRole>(generateMockUserRole());
  const [detectedObjects, setDetectedObjects] = useState<DetectedObject[]>(generateMockDetectedObjects());
  const [controlSettings, setControlSettings] = useState<ControlSettings>(generateMockControlSettings());
  const [isMinimized, setIsMinimized] = useState(false);
  const [currentView, setCurrentView] = useState<'main' | 'settings' | 'emergency'>('main');
  const [isConnected, setIsConnected] = useState(false);
  const [connectionStatus, setConnectionStatus] = useState<'connecting' | 'connected' | 'disconnected' | 'error'>('connecting');

  // 添加新系统消息 - 移到最前面避免声明前使用
  const addSystemMessage = useCallback((message: Omit<SystemMessage, 'id' | 'timestamp'>) => {
    const newMessage: SystemMessage = {
      ...message,
      id: Date.now().toString(),
      timestamp: new Date(),
      acknowledged: false,
    };
    setSystemMessages(prev => [newMessage, ...prev].slice(0, 10)); // 最多保留10条消息
  }, []);

  // 模拟与智驾域通信连接
  useEffect(() => {
    const connectToVehicleDomain = async () => {
      setConnectionStatus('connecting');
      
      // 模拟连接过程
      setTimeout(() => {
        setIsConnected(true);
        setConnectionStatus('connected');
        addSystemMessage({
          type: 'success',
          title: '智驾域连接成功',
          message: '已成功连接到车辆智驾域，开始获取实时数据',
          acknowledged: false
        });
      }, 2000);
    };

    connectToVehicleDomain();
  }, [addSystemMessage]);

  // 实时更新车辆状态 - 仅在连接成功后
  useEffect(() => {
    if (!isConnected) return;

    const interval = setInterval(() => {
      setVehicleStatus(generateMockVehicleStatus());
      setDetectedObjects(generateMockDetectedObjects());
    }, 1000); // 更频繁的更新

    return () => clearInterval(interval);
  }, [isConnected]);

  // 更新导航信息 - 仅在连接成功后
  useEffect(() => {
    if (!isConnected) return;

    const interval = setInterval(() => {
      setNavigationInfo(generateMockNavigationInfo());
      setModuleStatus(generateMockModuleStatus());
    }, 3000);

    return () => clearInterval(interval);
  }, [isConnected]);



  // 确认消息
  const acknowledgeMessage = useCallback((messageId: string) => {
    setSystemMessages(prev =>
      prev.map(msg =>
        msg.id === messageId ? { ...msg, acknowledged: true } : msg
      )
    );
  }, []);

  // 切换用户角色
  const switchUserRole = useCallback((role: UserRole) => {
    setUserRole(role);
  }, []);

  // 切换视图
  const switchView = useCallback((view: 'main' | 'settings' | 'emergency') => {
    setCurrentView(view);
  }, []);

  // 切换最小化状态
  const toggleMinimized = useCallback(() => {
    setIsMinimized(prev => !prev);
  }, []);

  // 更新控制设置
  const updateControlSettings = useCallback((settings: Partial<ControlSettings>) => {
    setControlSettings(prev => ({ ...prev, ...settings }));
  }, []);

  // 紧急停车
  const emergencyStop = useCallback(() => {
    setVehicleStatus(prev => ({ ...prev, emergencyStop: true, autonomousMode: false }));
    addSystemMessage({
      type: 'error',
      title: '紧急停车',
      message: '车辆已执行紧急停车，请等待安全员处理',
      acknowledged: false
    });
  }, [addSystemMessage]);

  // 重新连接智驾域
  const reconnectToVehicleDomain = useCallback(async () => {
    setConnectionStatus('connecting');
    setIsConnected(false);
    
    setTimeout(() => {
      setIsConnected(true);
      setConnectionStatus('connected');
      addSystemMessage({
        type: 'success',
        title: '重新连接成功',
        message: '已重新连接到车辆智驾域',
        acknowledged: false
      });
    }, 1500);
  }, [addSystemMessage]);

  return {
    // 状态
    vehicleStatus,
    navigationInfo,
    moduleStatus,
    systemMessages,
    userRole,
    detectedObjects,
    controlSettings,
    isMinimized,
    currentView,
    isConnected,
    connectionStatus,

    // 方法
    addSystemMessage,
    acknowledgeMessage,
    switchUserRole,
    switchView,
    toggleMinimized,
    updateControlSettings,
    emergencyStop,
    reconnectToVehicleDomain,
  };
};
